package com.cc.visitor.utils;

import com.cc.alltype.alltype.FileUtils;
import com.cc.visitor.dao.VisitMapper;
import com.cc.visitor.entity.Visit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author chanchaw
 * @create 2025-01-10 10:52
 */
@Component
@Configuration
@EnableScheduling
public class ScheduleUtils {
    @Autowired
    private TemplateMsgUtils templateMsgUtils;
    @Autowired
    private VisitMapper visitMapper;
    @Value("${file.kaptcha.img-path}")
    private String kaptchaImgPath;
    private static final Logger logger = LoggerFactory.getLogger("schedule");
    @Lazy
    @Autowired
    private DynamicScheduledTaskRegistrar taskRegistrar;

    private static final String PUSH_MSG_AUDITED_UNUSE_CRON = "7 7 8 * * ?";// 每天早晨8点推送受访者前一天已审核但是未进场的访单
    private static final String AUTO_FINISH_ENTERED_CRON = "7 7 2 * * ?";// 每天凌晨2:07:07自动完工已进场访单
    private static final String DELETE_KAPTCHA_IMG_CRON = "* 0/11 * * * ?";// 每11分钟执行一次
    private static final String DELETE_KAPTCHA_IMG_CRON01 = "0/5 * * * * ?";// 每5秒钟执行一次
    @PostConstruct
    private void init() {
        taskRegistrar.addCronTask("每11分钟检查清理验证码图片文件", DELETE_KAPTCHA_IMG_CRON, () -> {
            logger.info("每11分钟检查清理验证码图片文件");
            try {
                delKaptchaImg();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });

        taskRegistrar.addCronTask("自动完工今日之前的已进场访单", AUTO_FINISH_ENTERED_CRON, () -> {
            logger.info("自动完工今日之前的已进场访单");
            Integer i = visitMapper.autoFinishEntered();
            logger.info("自动完工今日之前的已进场访单数：" + i);
        });

        taskRegistrar.addCronTask("前一天已审核未进场的访单", PUSH_MSG_AUDITED_UNUSE_CRON, () -> {
            logger.info("前一天已审核未进场的访单");
            templateMsgUtils.pushIntervieweeAuditedUnUse();
        });
    }

    // 删除距离目前时间超过24小时的验证码图片文件
    private void delKaptchaImg() throws IOException {
        List<File> files = FileUtils.listFiles(kaptchaImgPath);
        if(files.size() == 0) return;

        for (File file : files) {
            boolean b = file.isFile();
            if(!b) continue;

            Path path = Paths.get(file.getAbsolutePath());
            BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
            FileTime fileTime = attrs.creationTime();
            LocalDateTime fileCreateTime = fileTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
            System.out.println(file.getName() + "创建时间：" + fileCreateTime);
            int i = LocalDateTime.now().compareTo(fileCreateTime);
            if(i>=1) file.delete();// 超过1天时间则删除该验证码图片文件
        }
    }

}
